const express = require('express')
const tagRouter = express.Router()
const tagModel = require('../modules/tag_tab')
const tagRelationModel = require('../modules/tag_relation_tab')
const { raw } = require('body-parser')
const Sequelize = require('sequelize')
const Op = Sequelize.Op


//分页和模糊查询
// http://localhost:8089/student/search?pageNum=1&pageSize=10?search=''
tagRouter.get('/search', async (req, res, next) => {

  try {
    const page = parseInt(req.query.pageNum) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const offset = (page - 1) * pageSize;
    const tag_name = req.query.labelName
    const creater_type = req.query.userType
    const where = {
      is_delete: 0,
    }
    if (creater_type) {
      where.creater_type = creater_type
    }
    if (tag_name) {
      where.tag_name = {
        [Op.like]: `%${tag_name}%`
      }
    }
    const tagLen = await tagModel.findAll({
      raw: true,
      where
    })
    const result = await tagModel.findAll({
      raw: true,
      offset,
      limit: pageSize,
      where: where
    });
    res.json({
      code: 1,
      msg: '请求成功',
      data: result,
      page,
      pageSize,
      total: tagLen.length
    });
  } catch (err) {
    next(err);
  }
})

//根据tag_id删除标签，假删除
tagRouter.post('/delete', async (req, res, next) => {
  try {
    const { tag_id } = req.query;
    const tag = await tagModel.findOne({ where: { tag_id, is_delete: 0 } });
    if (!tag) {
      res.json({
        code: 0,
        msg: '该标签不存在'
      });
    }
    await tag.update({ is_delete: 1 });
    res.json({
      code: 1,
      msg: '请求成功',
    });
  } catch (err) {
    next(err);
  }

})

//根据tag_id获取标签详情
tagRouter.get('/detail', async (req, res, next) => {
  try {
    const { tag_id } = req.query;
    const tag = await tagModel.findOne({ where: { tag_id, is_delete: 0 } });
    if (!tag) {
      res.json({
        code: 0,
        msg: '该标签不存在'
      });
    }
    res.json({
      code: 1,
      msg: '请求成功',
      data: tag
    });
  } catch (err) {
    next(err);
  }
})

//根据id修改标签名
tagRouter.post('/modify', async (req, res, next) => {
  try {
    const { tag_id, tag_name } = req.query;
    const tag = await tagModel.findOne({ where: { tag_id, is_delete: 0 } });
    if (!tag) {
      res.json({
        code: 0,
        msg: '该标签不存在'
      });
    }
    await tag.update({ tag_name: tag_name })
    res.json({
      code: 1,
      msg: '请求成功',
    });
  } catch (err) {
    next(err);
  }
})
//新增标签
tagRouter.post('/add', async (req, res, next) => {
  try {
    const tags = await tagModel.findAll({ raw: true })
    let tag_id = tags.length > 0 ? tags.sort((a, b) => b.tag_id - a.tag_id)[0].tag_id + 1 : 1
    const { create_time, tag_name, creater_type, nickname } = req.query;
    const result = await tagModel.create({ create_time, tag_name, creater_type, nickname, tag_id });
    res.json({
      code: 1,
      msg: '请求成功',
      data:result
    })
  } catch (err) {
    next(err);
  }
})
//批量删除,假删除
tagRouter.post('/delete/amount', async (req, res, next) => {
  try {
    const { tags } = req.query;
    tags.forEach(async (item) => {
      const tag = await tagModel.findOne({ where: { tag_id: item.tag_id, is_delete: 0 } });
      if (!tag) {
        res.json({
          code: 0,
          msg: '该标签不存在'
        });
      }
      await tag.update({ is_delete: 1 });
    })
    res.json({
      code: 1,
      msg: '请求成功'
    })
  } catch (err) {
    next(err);
  }
})
//标签创建统计
tagRouter.get('/tag/number', async (rqe, res, next) => {
  try {
    const where = {
      is_delete: 0
    }
    const tags = await tagModel.findAll({ rwa: true, where })
    const tag_admin = tags.filter((item) => item.creater_type == 1)
    const tag_user = tags.filter((item) => item.creater_type == 0)
    res.json({
      code: 1,
      msg: '请求成功',
      data: [
        {
          name: '管理员',
          value: tag_admin.length
        }, {
          name: '小程序用户',
          value: tag_user.length
        }
      ]
    })
  } catch (err) {
    next(err)
  }
})
//查找所有标签
tagRouter.get('/search/all', async (req, res, next) => {
  try {
    const result = await tagModel.findAll({
      raw: true,
      where: {
        is_delete: 0
      }
    })
    res.json({
      code: 1,
      msg: '请求成功',
      data: result
    })
  } catch (err) {
    next(err)
  }
})
//根据user_id查找所有标签
tagRouter.get('/search/user', async (req, res, next) => {
  try {
    const { user_id } = req.query
    const tagrRelations = await tagRelationModel.findAll({
      raw: true,
      where: {
        user_id,
        is_delete: 0
      },
      include: [
        {
          model: tagModel,
          required: true, // 如果需要强制关联
        },
      ],
    })

    res.json({
      code: 1,
      msg: '请求成功',
      data: tagrRelations
    })
  } catch (err) {
    next(err)
  }
})
//加入用户标签
tagRouter.post('/add/user', async (req, res, next) => {
  try {
    const { user_id, tag_id } = req.query
    const tagReals = await tagRelationModel.findAll({
      raw: true,
    })
    const tag_rela_id = tagReals.length > 0 ? tagReals.sort((a, b) => b.tag_rela_id - a.tag_rela_id)[0].tag_rela_id + 1 : 1
    const result = await tagRelationModel.create({
        is_delete: 0,
        tag_rela_id:tag_rela_id,
        user_id,
        tag_id
      
    })
    res.json({
      code: 1,
      msg: '请求成功'
    })
  } catch (err) {
    next(err)
  }
})
//根据id删除标签关系
tagRouter.post('/delete/relation',async(req,res,next) => {
  try{
    const { tag_rela_id } = req.query
    const result = await tagRelationModel.update({ is_delete: 1 }, {
      where: {
        tag_rela_id: tag_rela_id,
        is_delete: 0
      }
    });
    res.json({
      code:1,
      msg:'请求成功'
    })
  }catch(err){
    next(err)
  }
})
// 错误处理中间件
tagRouter.use((err, req, res, next) => {

  res.status(500).json({
    code: 0,
    msg: '服务器内部错误',
  });
});
module.exports = tagRouter